#include "commandutil.h"

#include <QProcess>
#include <QTextCodec>

QString CommandUtil::runCommand(const QString &commandLine, int timeout)
{
    QProcess process;
#ifdef Q_OS_WIN32
    process.start(commandLine);
#else
    QStringList options;
    options << "-c" << commandLine;
    process.start("/bin/bash", options);
#endif
    process.waitForFinished(timeout);
    QByteArray qbt = process.readAllStandardOutput().trimmed();
    QTextCodec *textCodec = QTextCodec::codecForName("utf-8");
    return textCodec->toUnicode(qbt);
}

QString CommandUtil::runCommand(const QString &program, const QStringList &params, int timeout)
{
    QProcess process;
    process.start(program, params);
    process.waitForFinished(timeout);
    QByteArray qbt = process.readAllStandardOutput().trimmed();
    QTextCodec *textCodec = QTextCodec::codecForName("system");
    return textCodec->toUnicode(qbt);
}

void CommandUtil::killProcessByName(const QString &name)
{
#ifdef Q_OS_WIN32
    CommandUtil::runCommand(QString("taskkill /f /im %1").arg(name));
#endif
#ifdef Q_OS_LINUX
    QString pid = CommandUtil::runCommand("pidof " + name);
    if (pid.isEmpty()) return;
    CommandUtil::runCommand("kill -9 " + pid);
#endif
}

#ifdef Q_OS_LINUX
QString CommandUtil::runCommandByUser(const QString &commandLine, const QString &userName, int timeout)
{
    QProcess process;
    QString cmd = QString("su - %1 -c '%2'").arg(userName).arg(commandLine);
    QStringList options;
    options << "-c" << cmd;
    process.start("/bin/bash", options);
    process.waitForFinished(timeout);
    QByteArray qbt = process.readAllStandardOutput().trimmed();
    QTextCodec *textCodec = QTextCodec::codecForName("utf-8");
    return textCodec->toUnicode(qbt);
}

QString CommandUtil::getSessionBusPath(const QString &userName)
{
    QString cmd = QString("loginctl show-user %1 --property=RuntimePath | cut -d '=' -f 2").arg(userName);
    QString runtimePath = runCommand(cmd);
    return QString("unix:path=%1/bus").arg(runtimePath);
}
#endif
